from datetime import datetime
from app import db


class User(db.Model):
    """用户基本信息表"""
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    openid = db.Column(db.String(100), unique=True, nullable=False, comment='微信openid')
    unionid = db.Column(db.String(100), comment='微信unionid')
    phone = db.Column(db.String(20), unique=True, comment='手机号')
    email = db.Column(db.String(100), comment='邮箱')
    nickname = db.Column(db.String(50), nullable=False, comment='昵称')
    real_name = db.Column(db.String(50), comment='真实姓名')
    gender = db.Column(db.Integer, nullable=False, comment='性别：1男2女')
    birthday = db.Column(db.Date, comment='生日')
    age = db.Column(db.Integer, comment='年龄')
    height = db.Column(db.Integer, comment='身高cm')
    weight = db.Column(db.Integer, comment='体重kg')
    avatar = db.Column(db.String(255), comment='头像')
    signature = db.Column(db.String(500), comment='个性签名')
    province = db.Column(db.String(50), comment='省份')
    city = db.Column(db.String(50), comment='城市')
    district = db.Column(db.String(50), comment='区县')
    address = db.Column(db.String(200), comment='详细地址')
    
    # 状态相关
    status = db.Column(db.Integer, default=1, comment='状态：1正常2待审核3审核失败4封禁5注销')
    online_status = db.Column(db.Integer, default=1, comment='在线状态：1在线2离线3隐身')
    dating_status = db.Column(db.Integer, default=1, comment='交友状态：1单身2恋爱中3暂停4已婚')
    
    # 等级和积分
    level = db.Column(db.Integer, default=1, comment='用户等级')
    points = db.Column(db.Integer, default=0, comment='积分')
    
    # VIP相关
    vip_level = db.Column(db.Integer, default=0, comment='VIP等级：0普通1银卡2金卡3钻石')
    vip_expire_time = db.Column(db.DateTime, comment='VIP过期时间')
    
    # 认证相关
    is_verified = db.Column(db.Boolean, default=False, comment='是否实名认证')
    profile_complete = db.Column(db.Integer, default=0, comment='资料完整度百分比0-100')
    
    # 统计相关
    last_login_time = db.Column(db.DateTime, comment='最后登录时间')
    login_count = db.Column(db.Integer, default=0, comment='登录次数')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    profile = db.relationship('UserProfile', backref='user', uselist=False, cascade='all, delete-orphan')
    photos = db.relationship('UserPhoto', backref='user', cascade='all, delete-orphan')
    mate_criteria = db.relationship('MateCriteria', backref='user', uselist=False, cascade='all, delete-orphan')
    tags = db.relationship('UserTag', backref='user', cascade='all, delete-orphan')
    behaviors = db.relationship('UserBehavior', foreign_keys='UserBehavior.user_id', backref='user', cascade='all, delete-orphan')
    target_behaviors = db.relationship('UserBehavior', foreign_keys='UserBehavior.target_user_id', backref='target_user', cascade='all, delete-orphan')
    verifications = db.relationship('UserVerification', backref='user', cascade='all, delete-orphan')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'openid': self.openid,
            'unionid': self.unionid,
            'phone': self.phone,
            'email': self.email,
            'nickname': self.nickname,
            'real_name': self.real_name,
            'gender': self.gender,
            'gender_text': self.get_gender_text(),
            'birthday': self.birthday.strftime('%Y-%m-%d') if self.birthday else None,
            'age': self.age,
            'height': self.height,
            'weight': self.weight,
            'avatar': self.avatar,
            'signature': self.signature,
            'province': self.province,
            'city': self.city,
            'district': self.district,
            'address': self.address,
            'status': self.status,
            'status_text': self.get_status_text(),
            'online_status': self.online_status,
            'online_status_text': self.get_online_status_text(),
            'dating_status': self.dating_status,
            'dating_status_text': self.get_dating_status_text(),
            'level': self.level,
            'points': self.points,
            'vip_level': self.vip_level,
            'vip_level_text': self.get_vip_level_text(),
            'vip_expire_time': self.vip_expire_time.strftime('%Y-%m-%d %H:%M:%S') if self.vip_expire_time else None,
            'is_verified': self.is_verified,
            'profile_complete': self.profile_complete,
            'last_login_time': self.last_login_time.strftime('%Y-%m-%d %H:%M:%S') if self.last_login_time else None,
            'login_count': self.login_count,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
    
    def get_gender_text(self):
        """获取性别文本"""
        gender_map = {1: '男', 2: '女'}
        return gender_map.get(self.gender, '未知')
    
    def get_status_text(self):
        """获取状态文本"""
        status_map = {1: '正常', 2: '待审核', 3: '审核失败', 4: '封禁', 5: '注销'}
        return status_map.get(self.status, '未知')
    
    def get_online_status_text(self):
        """获取在线状态文本"""
        status_map = {1: '在线', 2: '离线', 3: '隐身'}
        return status_map.get(self.online_status, '离线')
    
    def get_dating_status_text(self):
        """获取交友状态文本"""
        status_map = {1: '单身', 2: '恋爱中', 3: '暂停交友', 4: '已结婚'}
        return status_map.get(self.dating_status, '单身')
    
    def get_vip_level_text(self):
        """获取VIP等级文本"""
        level_map = {0: '普通用户', 1: '银卡会员', 2: '金卡会员', 3: '钻石会员'}
        return level_map.get(self.vip_level, '普通用户')
    
    def is_vip(self):
        """判断是否为VIP用户"""
        if self.vip_level == 0:
            return False
        if self.vip_expire_time and self.vip_expire_time < datetime.now():
            return False
        return True
    
    def get_profile_completeness(self):
        """计算资料完整度"""
        total_fields = 10
        completed_fields = 0
        
        # 基础信息
        if self.nickname: completed_fields += 1
        if self.gender: completed_fields += 1
        if self.birthday: completed_fields += 1
        if self.height: completed_fields += 1
        if self.city: completed_fields += 1
        if self.avatar: completed_fields += 1
        if self.signature: completed_fields += 1
        
        # 详细资料
        if self.profile:
            if self.profile.education: completed_fields += 1
            if self.profile.occupation: completed_fields += 1
            if self.profile.self_intro: completed_fields += 1
        
        return int((completed_fields / total_fields) * 100)
    
    def update_profile_completeness(self):
        """更新资料完整度到数据库"""
        self.profile_complete = self.get_profile_completeness()
        return self.profile_complete
    
    def update_age(self):
        """根据生日更新年龄"""
        if self.birthday:
            today = datetime.now().date()
            age = today.year - self.birthday.year
            if today.month < self.birthday.month or (today.month == self.birthday.month and today.day < self.birthday.day):
                age -= 1
            self.age = age
    
    def __repr__(self):
        return f'<User {self.nickname}>' 